package com.example.springbootjwt.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/7/11 19:50
 */
public class JwtFilter extends GenericFilterBean
{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        //转成HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String authorization = req.getHeader("authorization");
        System.out.println("authorization:"+authorization);
        Jws<Claims> jws = Jwts.parser().setSigningKey("leo123456").
                parseClaimsJws(authorization.replace("Bearer", ""));
        Claims body = jws.getBody();
        System.out.println("body:"+body);
        //body:{authorities=ROLE_admin,, sub=admin, exp=1594484790}
        String username = body.getSubject();
        System.out.println("username:"+username);
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(((String) body.get("authorities")));

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, "", authorities);
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
